import hashlib

from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from pet_admin.models import Users, GoodType, Goods


def index(request):
    """
        定位首页
    """
    return redirect(reverse('web_index'))


def web_index(request):
    """
        定位首页
    """
    # 获取商品类别和类别对应商品
    # 获取所有正常状态的商品类型
    good_types = GoodType.objects.filter(type_status__lt=9)
    good_typelist = dict()
    goodlist = dict()
    # 获取所有商品类别
    for goodType in good_types:
        # 把商品类别封装到一个字典中，把商品放到goods中
        goods = {"type_id": goodType.type_id, "type_name": goodType.type_name, "goods": []}
        # 获取所有当前分类的正常使用的商品
        goodlists = Goods.objects.filter(type_id=goodType.type_id, good_status=0)
        # 遍历商品信息
        for good in goodlists:
            # 把商品信息转化为字典格式放到goods中
            # print(good.toDict())
            goods["goods"].append(good.toDict())
            goodlist[good.good_id] = good.toDict()
        good_typelist[goodType.type_id] = goods

    # 把处理好的品类，商品资料存入session
    print(good_typelist)
    request.session['good_typelist'] = good_typelist
    request.session['goodlist'] = goodlist
    # 处理封装到session中商品类型以及商品信息数据
    context = {"goods": request.session.get("good_typelist", {}).items()}
    # print(context)
    return render(request, 'pet_web/index.html', context)


def login(request):
    """
        定位登陆页
    """
    return render(request, 'pet_web/login.html')


def verify(request):
    """
        生成验证码
    """
    # 引入随机函数模块
    import random
    from PIL import Image, ImageDraw, ImageFont
    # 定义变量，用于画面的背景色、宽、高
    # bgcolor = (random.randrange(20, 100), random.randrange(
    #    20, 100),100)
    bgcolor = (242, 164, 247)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    str1 = '0123456789'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('static/arial.ttf', 21)
    # font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')


def dologin(request):
    try:

        # 根据登陆账号查询登陆者信息
        user = Users.objects.get(user_account=request.POST["user_account"])
        # 判断当前账号是否有效
        if user.user_type != 9:
            # 判断登陆密码的正确
            # 密码md5处理
            md5Pw = hashlib.md5()
            s = request.POST["user_password"] + user.user_password_salt  # 从表单中获取密码且加干扰值
            md5Pw.update(s.encode('utf-8'))
            if user.user_password_hash == md5Pw.hexdigest():  # 比较数据库密码和用户输入的密码
                if request.POST['code'] != request.session['verifycode']:
                    return redirect(reverse('web_login') + "?errinfo=2")
                print("登陆成功")
                # 把当前用户信息以webUser写入session中
                request.session['webUser'] = user.toDict()
                # 重定向到后台首页
                return redirect(reverse('web_index'))
            else:
                return redirect(reverse('web_login') + "?errinfo=3")
        else:
            return redirect(reverse('web_login') + "?errinfo=4")
            # 对比验证码

    except Exception as err:
        print(err)
        return redirect(reverse('web_login') + "?errinfo=1")


def logout(request):
    del request.session['webUser']
    return redirect(reverse('web_login'))
